<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js"></script>
	</head>
	<style>
		*{
			padding: 0;
			margin: 0;
			box-sizing: border-box;
			list-style: none;
		}
		ul{
			width: 600px;
			height: 600px;
			display: flex;
			flex-wrap: wrap;
		}
		li{
			width: 200px;
			height: 200px;
			background-image: url(img/bg.png);
			background-size: 600px;
			background-position: left top;
			/* border: 1px solid #fff; */
			/* bottom */
		}
		.blank{
			background-image: none;
		}
		.list-move{
			transition: .5s;
		}
	</style>
	<body>
		<div id='app'>
			<transition-group tag='ul' name="list">
				<li v-for='(item,index) in imgs'  :key='item.id'
				:style="{backgroundPosition:item.pos}" 
				:class='!item.pos ? "blank":""' @click="move(index)">
				</li>
			</transition-group>
			<button @click="start">开始游戏</button>
		</div>
		<script>
			Vue.createApp({
				data(){
					return{
						imgs:[
							{id:1,pos:'left top'},
							{id:2,pos:'center top'},
							{id:3,pos:'right top'},
							{id:4,pos:'left center'},
							{id:5,pos:'center'},
							{id:6,pos:'right center'},
							{id:7,pos:'left bottom'},
							{id:8,pos:'center bottom'},
							{id:9,pos:''},
						],
						mark:[
							{id:1,pos:'left top'},
							{id:2,pos:'center top'},
							{id:3,pos:'right top'},
							{id:4,pos:'left center'},
							{id:5,pos:'center'},
							{id:6,pos:'right center'},
							{id:7,pos:'left bottom'},
							{id:8,pos:'center bottom'},
							{id:9,pos:''},
						],
						m:0,
						s:0,
						timer:null   //定时器
					}
				},
				methods:{
					setTime(){
						timer=setInterval(()=>{
							this.s++
							if(this.s>=60){
								this.m++
								this.s=0
							}
						},1000)
					},
					isEnd(){
						for(let i=0;i<9;i++){
							if(this.imgs[i].id != this.mark[i].id){
								return false  //未成功
							}
						}
						clearInterval(timer)
						return true   //游戏成功
					},
					start(){
						this.imgs.sort(()=>Math.random()-0.5)
						this.s=0
						this.m=0
						this.setTime()
					},
					move(i){  //推方块
						var neb=[i-3,i+3,i-1,i+1]   //上下左右	
						if(parseInt(neb[2]/3) != parseInt(i/3)){
							neb[2]=-1 // 判断左边和i是不是同一行
						}
						if(parseInt(neb[3]/3) != parseInt(i/3)){
							neb[3]=-1 // 判断右边和i是不是同一行
						}			
						for(let j=0;j<4;j++){
							let next=neb[j]
							if(next >=0 && this.imgs[next].id == 9){
								this.imgs[next]=this.imgs[i] //将方块推到空白格
								this.imgs[i]={
									id:9,
									pos:''
								}  //新的空白格
								break
							}
						}
						if(this.isEnd()){
							setTimeout(()=>{
								alert('挑战成功！')
							}, 10);
						}
					}
				}
			}).mount('#app')
		</script>
	</body>
</html>